package com.yx.cloud.activity;

import static com.iot.common.utils.Event.MESSAGE_TYPE_REQUEST_MAP_AND_PATH;
import static com.iot.common.utils.Event.MESSAGE_TYPE_UPDATE_MAP;

import android.animation.Animator;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.CompoundButton;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.product.sweeper.bean.AreaInfo;
import com.iot.product.sweeper.bean.CleanRecord;
import com.iot.product.sweeper.bean.CleanSettings;
import com.iot.product.sweeper.bean.MapInfo;
import com.iot.product.sweeper.bean.Path;
import com.iot.product.sweeper.bean.Robot;
import com.iot.product.sweeper.bean.RobotStatus;
import com.iot.product.sweeper.bean.Room;
import com.iot.sdk.yugong.YuGongConstants;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.CleanParam;
import com.iot.sweeper.param.MapNameParam;
import com.iot.sweeper.param.RemoveMapParam;
import com.iot.sweeper.param.ResetMapParam;
import com.iot.sweeper.param.SaveMapParam;
import com.iot.sweeper.param.SetMapParam;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.bean.MapManagerItemBean;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.databinding.MapManagerBinding;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.utils.CommonConfirmDialog2;
import com.yx.cloud.utils.CommonInputTextDialog;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.PopupWindowRight;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.utils.ToastUtil;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 地图管理界面
 */
public class MapManagerActivity extends BaseActivity implements PopupWindowRight.ClickCallback, View.OnClickListener {
    public static final int NO_MAP = 0;//没有地图
    public static final int HAS_MAP_NO_DATA = 1;//有地图，数据为空
    public static final int HAS_MAP = 2;//有地图有数据

    private static final String TAG = "MapManagerActivity";
    public static volatile boolean requestMap = false;
    PopupWindowRight popupWindowRight;
    boolean restrictNotRead;
    boolean roomNotRead;
    boolean customNotRead;
    boolean mapSaveNotRead;
    private List<MapManagerItemBean> multiMaplist;
    private List<CleanRecord> cloudMaplist;
    private MapManagerItemBean selectItemBean;
    private String selectedMapName;
    private boolean refreshCurrentMap = true;
    private boolean setCurrentMapSuccess = false;
    private boolean resetMapSuccess = false;
    private JSONObject productConfig;
    private LoadProgressDialog loadProgressDialog;
    private boolean saving = false;
    private boolean resetting = false;
    private boolean renaming = false;
    private boolean deleting = false;
    private boolean settingMap = false;
    private Handler handler;
    private MapManagerBinding binding;
    private int position = 0;
    private Robot robot;
    private CleanSettings settings;
    private List<MapNameParam> mapNames;

    @Override
    public void onCreate() {
        binding = MapManagerBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        productConfig = AppContext.getConfig();
        initView();
        requestMap = true;
        handler = new MainHandler(this);
        handler.sendEmptyMessage(MESSAGE_TYPE_REQUEST_MAP_AND_PATH);
    }

    private void requestMap() {
        if (requestMap) {
            Log.d("requestMap", "===== request map ====");
            AppContext.getProductService().requestMap();
            handler.removeMessages(MESSAGE_TYPE_REQUEST_MAP_AND_PATH);
            handler.sendEmptyMessageDelayed(MESSAGE_TYPE_REQUEST_MAP_AND_PATH, YuGongConstants.DURATION_REQUEST_DATA);
        }
    }


    private void initView() {
        boolean showCustom = AppContext.get().getCurrentDevice().getCleanSettings().isCustomSwitch();
        binding.targetView.setBackgroundColor(getResources().getColor(R.color.background_color));
        binding.targetView.setMinCleanAreaSize((float) productConfig.optDouble(ProductConfigConstants.minCleanAreaSize));
        binding.targetView.setRoomTagMode(true, false, false, false, showCustom && (position == 0), productConfig.optBoolean(ProductConfigConstants.custom_cleanTimes), productConfig.optBoolean(ProductConfigConstants.custom_water));

        restrictNotRead = SharedPrefsUtil.getValue(this, Constants.NOT_READ_TAG, Constants.KEY_RESTRICT_EDIT_NOT_READ, true);
        if (restrictNotRead) {
            binding.ivRestrictEditNotRead.setVisibility(View.VISIBLE);
        } else {
            binding.ivRestrictEditNotRead.setVisibility(View.GONE);
        }
        roomNotRead = SharedPrefsUtil.getValue(this, Constants.NOT_READ_TAG, Constants.KEY_ROOM_EDIT_NOT_READ, true);
        if (roomNotRead) {
            binding.ivRoomEditNotRead.setVisibility(View.VISIBLE);
        } else {
            binding.ivRoomEditNotRead.setVisibility(View.GONE);
        }
        customNotRead = SharedPrefsUtil.getValue(this, Constants.NOT_READ_TAG, Constants.KEY_CUSTOM_EDIT_NOT_READ, true);
        if (customNotRead) {
            binding.ivCustomEditNotRead.setVisibility(View.VISIBLE);
        } else {
            binding.ivCustomEditNotRead.setVisibility(View.GONE);
        }
        mapSaveNotRead = SharedPrefsUtil.getValue(this, Constants.NOT_READ_TAG, Constants.KEY_MAP_SAVE_NOT_READ, true);
        if (mapSaveNotRead) {
            binding.ivMapSaveNotRead.setVisibility(View.VISIBLE);
        } else {
            binding.ivMapSaveNotRead.setVisibility(View.INVISIBLE);
        }

        if (AppContext.get().getCurrentDevice().getMap().getRoom().size() == 0) {
            binding.rlRoomEdit.setVisibility(View.GONE);
            binding.rlCustomEdit.setVisibility(View.GONE);
        }

        loadProgressDialog = new LoadProgressDialog(this, 6);

        binding.ivMapRefresh.setTag("refresh");
        binding.ivMapSave.setTag("save");

        binding.cb3d2dSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    if (hasMap() == HAS_MAP) {
                        binding.targetView.setVisibility(View.GONE);
                        binding.map3dTargetView.setVisibility(View.VISIBLE);
                        binding.map3dTargetView.refreshMap(AppContext.get().getCurrentDevice().getMap());
                        binding.llRotateMap.setVisibility(View.GONE);
                        binding.tv3d2dSwitch.setText(getString(R.string.dd_switch));
                    } else {
                        ToastUtil.showShort(MapManagerActivity.this, R.string.MM_NoContent);
                    }
                } else {
                    binding.targetView.setVisibility(View.VISIBLE);
                    binding.map3dTargetView.setVisibility(View.GONE);
                    binding.llRotateMap.setVisibility(View.VISIBLE);
                    binding.targetView.initMap(AppContext.get().getCurrentDevice().getMap());
                    binding.tv3d2dSwitch.setText(getString(R.string.ddd_switch));
                }
            }
        });

        robot = AppContext.get().getCurrentDevice();
        if (robot != null) {
            if (productConfig.optBoolean(ProductConfigConstants.rotate_map)) {
                binding.ivRotateMap.setVisibility(View.VISIBLE);
            } else {
                binding.ivRotateMap.setVisibility(View.GONE);
            }
            if (productConfig.optBoolean(ProductConfigConstants.ddd_2_dd)) {
                binding.cb3d2dSwitch.setVisibility(View.VISIBLE);
            } else {
                binding.cb3d2dSwitch.setVisibility(View.GONE);
            }
        }
    }

    private void showLoadingDialog() {
        if (loadProgressDialog != null) {
            if (loadProgressDialog.isShowing()) {
                loadProgressDialog.dismiss();
            }
        }
        loadProgressDialog = new LoadProgressDialog(this, 6);
        loadProgressDialog.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                loadProgressDialog.dismiss();
                Log.i(TAG, "动画执行完毕--------------------------------------------- : ");
                if (hasMap() == NO_MAP) {
                    binding.flBottom.setVisibility(View.GONE);
                    binding.llBtnCreateMap.setVisibility(View.VISIBLE);
                    if (multiMaplist != null) {
                        if (multiMaplist.size() <= 1) {
                            binding.ivMultiMap.setVisibility(View.GONE);
                            binding.llBtnCreateMap.setVisibility(View.VISIBLE);
                        } else {
                            binding.ivMultiMap.setVisibility(View.VISIBLE);
                            showMultiMapView();
                            binding.llBtnCreateMap.setVisibility(View.GONE);
                            hideCreateMapBtn();
                        }
                    } else {
                        binding.ivMultiMap.setVisibility(View.GONE);
                        binding.llBtnCreateMap.setVisibility(View.VISIBLE);
                    }
                    binding.llNoMap.setVisibility(View.VISIBLE);
                    binding.ivMapSave.setVisibility(View.GONE);
                    binding.ivMapRefresh.setVisibility(View.GONE);
                    binding.ivMapSaveNotRead.setVisibility(View.INVISIBLE);
                } else {
                    ToastUtil.showShort(MapManagerActivity.this, R.string.U_T_NetworkTimeout);
                    saving = false;
                    resetting = false;
                    renaming = false;
                    deleting = false;
                    settingMap = false;
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
        loadProgressDialog.show();
    }

    private void showMultiMapView() {
        //在线
        robot = AppContext.get().getCurrentDevice();
        if (robot != null) {
            if (!productConfig.optBoolean(ProductConfigConstants.robotSetting_multiMap)) {//没有多楼层地图开关，就默认显示多地图
                //TODO 根据当前地图是否保存，来设置tag
                //binding.ivMultiMap.setVisibility(View.VISIBLE);
                //binding.ivMapSave.setVisibility(View.VISIBLE);
            } else {
                settings = robot.getCleanSettings();
                if (settings.isOpenMultiMap()) {
                    binding.ivMultiMap.setVisibility(View.VISIBLE);
                    binding.ivMapRefresh.setVisibility(View.VISIBLE);
                    binding.ivMapSave.setVisibility(View.VISIBLE);
                    mapSaveNotRead = SharedPrefsUtil.getValue(this, Constants.NOT_READ_TAG, Constants.KEY_MAP_SAVE_NOT_READ, true);
                    if (mapSaveNotRead) {
                        binding.ivMapSaveNotRead.setVisibility(View.VISIBLE);
                    } else {
                        binding.ivMapSaveNotRead.setVisibility(View.INVISIBLE);
                    }
                } else {
                    binding.ivMapSave.setVisibility(View.GONE);
                    binding.ivMapSaveNotRead.setVisibility(View.INVISIBLE);
                    binding.ivMultiMap.setVisibility(View.GONE);
                    if (popupWindowRight != null) {
                        popupWindowRight.dismiss();
                    }
                }
            }
        }
    }

    private void hideCreateMapBtn() {
        robot = AppContext.get().getCurrentDevice();
        if (robot != null) {
            if (!productConfig.optBoolean(ProductConfigConstants.robotSetting_multiMap)) {//没有多楼层地图开关，就默认显示多地图
                //TODO 根据当前地图是否保存，来设置tag
                binding.llBtnCreateMap.setVisibility(View.GONE);
            } else {
                settings = robot.getCleanSettings();
                if (settings.isOpenMultiMap()) {
                    binding.llBtnCreateMap.setVisibility(View.GONE);
                } else {
                    if (multiMaplist != null && multiMaplist.size() <= 2) {
                        binding.llBtnCreateMap.setVisibility(View.VISIBLE);
                    } else {
                        binding.llBtnCreateMap.setVisibility(View.GONE);
                    }
                }
            }
        }
    }

    private void showRightDialog() {
        if (popupWindowRight == null) {
            popupWindowRight = new PopupWindowRight(MapManagerActivity.this, R.layout.popup_dialog_right, multiMaplist);
            popupWindowRight.setAnimationStyle(R.style.contextMenuAnim);
            popupWindowRight.setClickCallback(this);
        }
        if (popupWindowRight != null) {
            popupWindowRight.setFocusable(true);
        }
        popupWindowRight.showAtLocation(getWindow().getDecorView(), Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
    }

    private void refreshCurrentMap() {
        if (multiMaplist != null && multiMaplist.size() > 0) {
            MapManagerItemBean currentMap = new MapManagerItemBean();
            currentMap.setName(getString(R.string.MM_Current));
            currentMap.setMap(AppContext.get().getCurrentDevice().getMap());
            multiMaplist.set(0, currentMap);
            if (popupWindowRight != null) {
                popupWindowRight.updateData(multiMaplist);
            }
            Log.d(TAG, "extend is size is" + multiMaplist.size());
        }
    }

    private void refreshCurrentMapView() {
        switch (hasMap()) {
            case NO_MAP:
                binding.flBottom.setVisibility(View.GONE);

                if (multiMaplist.size() == 1) {
                    binding.ivMultiMap.setVisibility(View.GONE);
                    binding.llBtnCreateMap.setVisibility(View.VISIBLE);
                } else {
                    binding.ivMultiMap.setVisibility(View.VISIBLE);
                    showMultiMapView();
                    hideCreateMapBtn();
                }
                binding.llNoMap.setVisibility(View.VISIBLE);
                binding.ivMapSaveNotRead.setVisibility(View.GONE);
                binding.ivMapSave.setVisibility(View.GONE);
                binding.ivMapRefresh.setVisibility(View.INVISIBLE);
                Log.d("pppppp", "NO_MAP");
                break;
            case HAS_MAP_NO_DATA:
                if (loadProgressDialog.isShowing() && !saving && !deleting && !renaming && !settingMap && !resetting ){
                    loadProgressDialog.dismiss();
                }
                if (multiMaplist.size() == 1) {
                    binding.ivMultiMap.setVisibility(View.GONE);
                    binding.llBtnCreateMap.setVisibility(View.VISIBLE);
                } else {
                    binding.ivMultiMap.setVisibility(View.VISIBLE);
                    showMultiMapView();
                    hideCreateMapBtn();
                }
                binding.llNoMap.setVisibility(View.VISIBLE);
                binding.flBottom.setVisibility(View.GONE);
                binding.ivMapSave.setVisibility(View.GONE);
                binding.ivMapRefresh.setVisibility(View.GONE);
                binding.ivMapSaveNotRead.setVisibility(View.INVISIBLE);
                Log.d("pppppp", "HAS_MAP_NO_DATA");
                break;
            case HAS_MAP:
                if (loadProgressDialog.isShowing() && !saving && !deleting && !renaming && !settingMap && !resetting ) {
                    loadProgressDialog.dismiss();
                }
                if (binding.llNoMap.getVisibility() == View.VISIBLE) {
                    binding.llNoMap.setVisibility(View.GONE);
                }

                binding.ivMultiMap.setVisibility(View.VISIBLE);
                binding.ivMapSave.setVisibility(View.VISIBLE);
                binding.ivMapRefresh.setVisibility(View.VISIBLE);

                mapSaveNotRead = SharedPrefsUtil.getValue(this, Constants.NOT_READ_TAG, Constants.KEY_MAP_SAVE_NOT_READ, true);
                if (mapSaveNotRead) {
                    binding.ivMapSaveNotRead.setVisibility(View.VISIBLE);
                } else {
                    binding.ivMapSaveNotRead.setVisibility(View.INVISIBLE);
                }

                showMultiMapView();
                binding.llBtnCreateMap.setVisibility(View.GONE);
                binding.targetView.initMap(AppContext.get().getCurrentDevice().getMap());
                if (AppContext.get().getCurrentDevice().getMap().getRoom().size() != 0) {
                    binding.flBottom.setVisibility(View.VISIBLE);
                    binding.rlRoomEdit.setVisibility(View.VISIBLE);
                    binding.rlCustomEdit.setVisibility(View.VISIBLE);
                    if (productConfig.optBoolean(ProductConfigConstants.furniture_edit)) {
                        binding.rlFurnitureEdit.setVisibility(View.VISIBLE);
                    } else {
                        binding.rlFurnitureEdit.setVisibility(View.GONE);
                    }
                    Log.d("pppppp", "map room size > 0");
                } else {
                    binding.flBottom.setVisibility(View.VISIBLE);
                    binding.rlRoomEdit.setVisibility(View.GONE);
                    binding.rlCustomEdit.setVisibility(View.GONE);
                    binding.rlFurnitureEdit.setVisibility(View.GONE);
                    Log.d("pppppp", "map room size == 0");
                }
                if (multiMaplist != null && multiMaplist.size() >= 1) {
                    MapManagerItemBean currentMap = new MapManagerItemBean();
                    currentMap.setName(getString(R.string.MM_Current));
                    currentMap.setMap(AppContext.get().getCurrentDevice().getMap());
                    multiMaplist.set(0, currentMap);
                }
                Log.d("pppppp", "HAS_MAP");
                break;
        }

        refreshCurrentMap = true;

        binding.llBtnSetMapOk.setVisibility(View.GONE);
        binding.ivMapRefresh.setImageResource(R.mipmap.map_refresh);
        binding.ivMapRefresh.setTag("refresh");
        binding.ivMapSave.setImageResource(R.mipmap.map_save);
        binding.ivMapSave.setTag("save");
        binding.tvMapManagerName.setText(getString(R.string.MM_Current));

        if (!productConfig.optBoolean(ProductConfigConstants.hasMultiMap)) {
            binding.flBottom.setVisibility(View.GONE);
            binding.ivMultiMap.setVisibility(View.GONE);
            binding.ivMapSave.setVisibility(View.GONE);
            binding.ivMapRefresh.setVisibility(View.GONE);
            binding.ivMapSaveNotRead.setVisibility(View.INVISIBLE);
        }

        if (position != 0) {
            popupWindowRight.selectItem(position);
        }
    }

    private void initData() {
        switch (hasMap()) {
            case NO_MAP:
            case HAS_MAP_NO_DATA:
                if (!productConfig.optBoolean(ProductConfigConstants.hasMap)) {
                    binding.llBtnCreateMap.setVisibility(View.VISIBLE);
                    binding.llNoMap.setVisibility(View.VISIBLE);
                    break;
                }

                binding.flBottom.setVisibility(View.GONE);
                binding.llNoMap.setVisibility(View.VISIBLE);
                binding.ivMapSave.setVisibility(View.GONE);
                binding.ivMapRefresh.setVisibility(View.GONE);
                binding.ivMapSaveNotRead.setVisibility(View.INVISIBLE);
                AppContext.getProductService().requestMap();
                break;
            case HAS_MAP:
                if (loadProgressDialog.isShowing()) {
                    loadProgressDialog.dismiss();
                }
                if (binding.llNoMap.getVisibility() == View.VISIBLE) {
                    binding.llNoMap.setVisibility(View.GONE);
                }

                binding.ivMultiMap.setVisibility(View.VISIBLE);
                binding.ivMapSave.setVisibility(View.VISIBLE);
                binding.ivMapRefresh.setVisibility(View.VISIBLE);

                mapSaveNotRead = SharedPrefsUtil.getValue(this, Constants.NOT_READ_TAG, Constants.KEY_MAP_SAVE_NOT_READ, true);
                if (mapSaveNotRead) {
                    binding.ivMapSaveNotRead.setVisibility(View.VISIBLE);
                } else {
                    binding.ivMapSaveNotRead.setVisibility(View.INVISIBLE);
                }

                showMultiMapView();

                binding.targetView.initMap(AppContext.get().getCurrentDevice().getMap());
                if (AppContext.get().getCurrentDevice().getMap().getRoom().size() != 0) {
                    binding.flBottom.setVisibility(View.VISIBLE);
                    binding.rlRoomEdit.setVisibility(View.VISIBLE);
                    binding.rlCustomEdit.setVisibility(View.VISIBLE);
                } else {
                    binding.flBottom.setVisibility(View.VISIBLE);
                    binding.rlRoomEdit.setVisibility(View.GONE);
                    binding.rlCustomEdit.setVisibility(View.GONE);
                }
                break;
        }
        if (!productConfig.optBoolean(ProductConfigConstants.hasMultiMap)) {
            binding.flBottom.setVisibility(View.GONE);
            binding.ivMultiMap.setVisibility(View.GONE);
            binding.ivMapSave.setVisibility(View.GONE);
            binding.ivMapRefresh.setVisibility(View.GONE);
            binding.ivMapSaveNotRead.setVisibility(View.INVISIBLE);
        }

        binding.ivMapManagerReturn.setOnClickListener(this);
        binding.ivMapSave.setOnClickListener(this);
        binding.ivMapRefresh.setOnClickListener(this);
        binding.ivMultiMap.setOnClickListener(this);
        binding.rlMapContent.setOnClickListener(this);
        binding.cb3d2dSwitch.setOnClickListener(this);
        binding.rlAreaEdit.setOnClickListener(this);
        binding.rlRestrictEdit.setOnClickListener(this);
        binding.rlRoomEdit.setOnClickListener(this);
        binding.rlFurnitureEdit.setOnClickListener(this);
        binding.rlCustomEdit.setOnClickListener(this);
        binding.btnSetMapOk.setOnClickListener(this);
        binding.btnCreateMap.setOnClickListener(this);
        binding.ivRotateMap.setOnClickListener(this);

    }

    private int hasMap() {
        MapInfo mapInfo = AppContext.get().getCurrentDevice().getMap().getMap();
        if (mapInfo.mapId < 0 || (mapInfo.width == 0 && mapInfo.height == 0)) {
            return NO_MAP;
        } else if (AppContext.get().getCurrentDevice().getMap().getMap().mapData == null || AppContext.get().getCurrentDevice().getMap().getMap().mapData.length < 3) {
            return HAS_MAP_NO_DATA;
        }
        return HAS_MAP;
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestMap = true;
        EventBus.getDefault().register(this);

        if (position == 0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Event.newBuilder().type(Event.MESSAGE_TYPE_GET_MAP_LIST).result(true).send();
                }
            }).start();

            initData();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (multiMaplist != null) {
            multiMaplist.clear();
        }
        requestMap = false;
        if (handler != null) {
            handler.removeMessages(MESSAGE_TYPE_REQUEST_MAP_AND_PATH);
        }
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_map_manager_return:
                finish();
                break;
            case R.id.btn_create_map:
                if (productConfig.optBoolean(ProductConfigConstants.create_map_quickly)) {
                    //AppContext.getProductService().createMap();
                } else {
                    CleanParam param = new CleanParam();
                    param.setType(RobotStatus.MODE_AUTO_CLEAN);
                    AppContext.getProductService().startSweep(param);
                    finish();
                }
                break;
            case R.id.iv_map_save:
                if (binding.ivMapSave.getTag().equals("save")) {
                    if (multiMaplist != null && multiMaplist.size() >= 6) {//当前地图+云端5张
                        ToastUtil.showShort(MapManagerActivity.this, R.string.MM_T_SaveFull);
                    } else {
                        saveMap();
                    }
                    if (mapSaveNotRead) {
                        SharedPrefsUtil.putValue(this, Constants.NOT_READ_TAG, Constants.KEY_MAP_SAVE_NOT_READ, false);
                        binding.ivMapSaveNotRead.setVisibility(View.INVISIBLE);
                    }
                } else if (binding.ivMapSave.getTag().equals("edit")) {
                    String name = selectItemBean.getName();
                    CommonInputTextDialog.newBuilder()
                            .context(this)
                            .title(getString(R.string.MM_EditName))
                            .hint(name)
                            .callback(text -> {
                                        //TODO
                                        renameMap(text);
                                        selectedMapName = text;
                                        return true;
                                    }
                            ).build().show();
                }
                break;
            case R.id.iv_map_refresh:
                if (binding.ivMapRefresh.getTag().equals("refresh")) {
                    CommonConfirmDialog2.newBuilder()
                            .context(this)
                            .message(getString(R.string.MM_Reset_Tip))
                            .confirmCallback(new CommonConfirmDialog2.ConfirmCallback() {
                                @Override
                                public boolean onConfirm() {
                                    //TODO
                                    showLoadingDialog();
                                    resetMap();
                                    return true;
                                }

                                @Override
                                public boolean onCancel() {
                                    return true;
                                }
                            }).build().show();
                } else if (binding.ivMapRefresh.getTag().equals("delete")) {
                    CommonConfirmDialog2.newBuilder()
                            .context(this)
                            .message(getString(R.string.MM_Delete_Tip))
                            .confirmCallback(new CommonConfirmDialog2.ConfirmCallback() {
                                @Override
                                public boolean onConfirm() {
                                    //TODO
                                    removeMap();
                                    return true;
                                }

                                @Override
                                public boolean onCancel() {
                                    return true;
                                }
                            }).build().show();
                }
                break;
            case R.id.iv_multi_map:
                refreshCurrentMap();
                showRightDialog();
                getMultiMapDataList();
                break;
            case R.id.rl_map_content:
                break;
            case R.id.iv_rotate_map:
                //binding.targetView.rotate(90);
                break;
            case R.id.rl_area_edit:
                //2022-04-16徐老师说的
                //回冲中--暂停-不弹框--判断机型----公版的
                //清扫中-弹框-结束清扫--全机型
                Robot robot = AppContext.get().getCurrentDevice();
                int workState = robot.getRobotStatus().getWorkState();
                int workMode = robot.getRobotStatus().getWorkMode();
                if (workState == RobotStatus.STATE_WORKING) {
                    if (workMode == RobotStatus.MODE_AUTO_CLEAN
                            || workMode == RobotStatus.MODE_ROOM_CLEAN
                            || workMode == RobotStatus.MODE_CUSTOM_CLEAN
                            || workMode == RobotStatus.MODE_SPOT_CLEAN) {
                        currentTaskDialog(getString(R.string.H_EndTask), workMode);
                    } else if (workMode == RobotStatus.MODE_RECHARGE) {
                        if (productConfig.optBoolean(ProductConfigConstants.isEditMapNeedPauseRecharge)) {
                            AppContext.getProductService().pauseRecharge();
                        }

                        Intent_utils.enterIntent(this, AreaEditActivity.class);
                    }
                } else {
                    Intent_utils.enterIntent(this, AreaEditActivity.class);
                }

                break;
            case R.id.rl_restrict_edit:
                Intent_utils.enterIntent(this, RestrictedAreaSettingActivity.class);
                if (restrictNotRead) {
                    SharedPrefsUtil.putValue(this, Constants.NOT_READ_TAG, Constants.KEY_RESTRICT_EDIT_NOT_READ, false);
                    binding.ivRestrictEditNotRead.setVisibility(View.GONE);
                }
                break;
            case R.id.rl_room_edit:
                if (roomNotRead) {
                    SharedPrefsUtil.putValue(this, Constants.NOT_READ_TAG, Constants.KEY_ROOM_EDIT_NOT_READ, false);
                    binding.ivRoomEditNotRead.setVisibility(View.GONE);
                }
                Robot robot1 = AppContext.get().getCurrentDevice();
                int workState1 = robot1.getRobotStatus().getWorkState();
                int workMode1 = robot1.getRobotStatus().getWorkMode();
                if (workState1 == RobotStatus.STATE_WORKING) {
                    if (workMode1 == RobotStatus.MODE_AUTO_CLEAN
                            || workMode1 == RobotStatus.MODE_ROOM_CLEAN
                            || workMode1 == RobotStatus.MODE_CUSTOM_CLEAN
                            || workMode1 == RobotStatus.MODE_SPOT_CLEAN) {
                        currentTaskDialog1(getString(R.string.H_EndTask), workMode1);
                    } else if (workMode1 == RobotStatus.MODE_RECHARGE) {
                        if (productConfig.optBoolean(ProductConfigConstants.isEditMapNeedPauseRecharge)) {
                            AppContext.getProductService().pauseRecharge();
                        }

                        Intent_utils.enterIntent(this, RoomEditActivity.class);
                    }
                } else {
                    Intent_utils.enterIntent(this, RoomEditActivity.class);
                }
                break;
            case R.id.rl_furniture_edit:
                Intent_utils.enterIntent(this, FurnitureEditActivity.class);
                break;
            case R.id.rl_custom_edit:
                //TODO
                if (productConfig.optBoolean(ProductConfigConstants.isEditCustomNeedPause)) {
                    RobotStatus robotStatus = AppContext.get().getCurrentDevice().getRobotStatus();
                    if (robotStatus.getWorkState() == RobotStatus.STATE_WORKING) {
                        if (robotStatus.getWorkMode() == RobotStatus.MODE_RECHARGE) {
                            AppContext.getProductService().pauseRecharge();
                        } else {
                            AppContext.getProductService().pauseSweep();
                        }
                    }
                }
                Intent_utils.enterIntent(this, CustomModeActivity.class);
                if (customNotRead) {
                    SharedPrefsUtil.putValue(this, Constants.NOT_READ_TAG, Constants.KEY_CUSTOM_EDIT_NOT_READ, false);
                    binding.ivCustomEditNotRead.setVisibility(View.GONE);
                }
                break;
            case R.id.btn_set_map_ok:
                setCurrentMap();
                break;

        }
    }

    public boolean setCurrentMap() {
        //TODO 保存当前地图
        SetMapParam setMapParam = new SetMapParam();
        setMapParam.setMapId(selectItemBean.getMapId());
        setMapParam.setUrl(selectItemBean.getUrl());
        setMapParam.setExtend(selectItemBean.getExtend());
        AppContext.getProductService().setCurrentMap(setMapParam);
        showLoadingDialog();
        settingMap = true;
        return true;
    }

    public void saveMap() {
        //TODO 保存当前地图
        Robot robot = AppContext.get().getCurrentDevice();
        SaveMapParam saveMapParam = SaveMapParam.newBuilder().mapId("" + robot.getMap().getMap().mapId).build();
        AppContext.getProductService().saveMap(saveMapParam);
        showLoadingDialog();
        saving = true;
    }

    public void removeMap() {
        //TODO 保存当前地图
        RemoveMapParam removeMapParam = new RemoveMapParam();
        removeMapParam.setMapId(selectItemBean.getMapId());
        removeMapParam.setFileName(selectItemBean.getFileName());
        AppContext.getProductService().removeMap(removeMapParam);
        showLoadingDialog();
        deleting = true;

        MapNameParam mapNameParam = new MapNameParam();
        mapNameParam.setMapId(selectItemBean.getMapId());
        deleteMapName(mapNameParam);
    }

    private void modifyMapName(MapNameParam mapNameParam) {
        if (mapNames == null) {
            mapNames = new ArrayList<>();
        }
        int i;
        for (i = 0; i < mapNames.size(); i++) {
            if (mapNames.get(i).getMapId() == mapNameParam.getMapId()) {
                mapNames.get(i).setMapName(mapNameParam.getMapName());
                break;
            }
        }
        if (i >= mapNames.size()) {
            mapNames.add(mapNameParam);
        }
    }

    private void deleteMapName(MapNameParam mapNameParam) {
        if (mapNames != null) {
            int i;
            for (i = 0; i < mapNames.size(); i++) {
                if (mapNames.get(i).getMapId() == mapNameParam.getMapId()) {
                    mapNames.remove(i);
                    break;
                }
            }
        }
    }

    private String getMapName(int mapId) {
        String mapName = null;
        if (mapNames != null) {
            int i;
            for (i = 0; i < mapNames.size(); i++) {
                if (mapNames.get(i).getMapId() == mapId) {
                    mapName = mapNames.get(i).getMapName();
                }
            }
        }
        return mapName;
    }

    public void updateMapNameList() {
        AppContext.getProductService().saveMapListNames(mapNames);
    }

    //统一用涂鸦接口
    public void renameMap(String name) {
        //TODO 重命名当前地图
        MapNameParam mapNameParam = new MapNameParam();
        mapNameParam.setMapName(name);
        mapNameParam.setMapId(selectItemBean.getMapId());
        showLoadingDialog();
        renaming = true;
        modifyMapName(mapNameParam);
        updateMapNameList();
    }

    public void resetMap() {
        //TODO 重置当前地图
        ResetMapParam resetMapParam = new ResetMapParam();
        Robot robot = AppContext.get().getCurrentDevice();
        if (robot != null) {
            resetMapParam.setMapId(robot.getMap().getMap().mapId);
        }
        AppContext.getProductService().resetMap();
        Event.newBuilder().type(Event.MESSAGE_TYPE_RESET_MAP_SUCCESS).result(true).send();
        resetting = true;
    }

    public void getMultiMapDataList() {
        //TODO 获取多地图列表
        AppContext.getProductService().getMapList();
    }

    public void getMultiMapDataListDetail(List<CleanRecord> cleanRecords) {
        //TODO 获取多地图数据
        AppContext.getProductService().getMapListDetail(cleanRecords);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_MULTI_MAP_NAMES:
                if (event.isResult()) {
                    if (deleting) {
                        return;
                    }
                    if (mapNames != null) {
                        mapNames.clear();
                    } else {
                        mapNames = new ArrayList<>();
                    }
                    mapNames = (List<MapNameParam>) event.getContent();
                    Log.d(TAG, "aaaaaaaaaa mapNames size is " + mapNames.size());

                    if (renaming) {
                        loadProgressDialog.dismiss();
                        ToastUtil.showShort(MapManagerActivity.this, R.string.U_T_RobotName_Edit_Ok);
                        binding.tvMapManagerName.setText(selectedMapName);
                        selectItemBean.setName(selectedMapName);

                        renaming = false;
                        getMultiMapDataList();
                    }
                }
                break;
            case Event.MESSAGE_TYPE_GET_MULTI_MAP_LIST:
                getMultiMapDataListDetail((List<CleanRecord>) event.getContent());
                break;
            case Event.MESSAGE_TYPE_GET_MULTI_MAP:
                Log.d("testMultiMap", "MESSAGE_TYPE_GET_MULTI_MAP");
                if (event.isResult()) {
                    if (multiMaplist != null) {
                        multiMaplist.clear();
                    } else {
                        multiMaplist = new ArrayList<>();
                    }

                    MapManagerItemBean currentMap = new MapManagerItemBean();
                    currentMap.setName(getString(R.string.MM_Current));
                    currentMap.setMap(AppContext.get().getCurrentDevice().getMap());
                    multiMaplist.add(currentMap);

                    cloudMaplist = (List<CleanRecord>) event.getContent();
                    if (cloudMaplist != null && cloudMaplist.size() > 0) {
                        for (CleanRecord cleanRecord : cloudMaplist) {
                            MapManagerItemBean mapManagerItemBean = new MapManagerItemBean();
                            mapManagerItemBean.setMap(cleanRecord.getMap());
                            if (cleanRecord.getName() == null) {
                                mapManagerItemBean.setName(getString(R.string.MM_MapName).replace("{X}" , cleanRecord.getId()));
                            } else {
                                mapManagerItemBean.setName(cleanRecord.getName());
                            }

                            mapManagerItemBean.setUrl(cleanRecord.getUrl());
                            mapManagerItemBean.setMapId(Integer.parseInt(cleanRecord.getId()));
                            mapManagerItemBean.setExtend(cleanRecord.getExtend());
                            mapManagerItemBean.setFileName(cleanRecord.getFileName());

                            //从列表中匹配名字
                            String mapName = getMapName(mapManagerItemBean.getMapId());
                            if (mapName != null) {
                                mapManagerItemBean.setName(mapName);
                            }
                            Log.d(TAG, "extend is " + mapManagerItemBean.getExtend());
                            multiMaplist.add(mapManagerItemBean);
                        }
                    }

                    if (multiMaplist.size() <= 1) {
                        if (hasMap() != HAS_MAP) {
                            binding.ivMultiMap.setVisibility(View.GONE);
                            binding.llBtnCreateMap.setVisibility(View.VISIBLE);
                        }
                    } else {
                        binding.ivMultiMap.setVisibility(View.VISIBLE);
                        showMultiMapView();
                        binding.llBtnCreateMap.setVisibility(View.GONE);
                    }

                    if (popupWindowRight != null) {
                        popupWindowRight.updateData(multiMaplist);
                    } else {
                        popupWindowRight = new PopupWindowRight(MapManagerActivity.this, R.layout.popup_dialog_right, multiMaplist);
                        popupWindowRight.setAnimationStyle(R.style.contextMenuAnim);
                        popupWindowRight.setClickCallback(MapManagerActivity.this);
                    }
                }
                break;
            case Event.MSG_ROBOT_PATH:
                Log.d("path refresh", "recived MSG_ROBOT_PATH");
                if (refreshCurrentMap) {
                    Log.d("path refresh", "recived MSG_ROBOT_PATH and refresh path");
                    binding.targetView.refreshDeviceLayer(AppContext.get().getCurrentDevice().getMap().getSweeper());
                    binding.targetView.refreshPathLayer((Path) event.getContent());
                }
                break;
            case Event.MSG_ROBOT_MAP:
                //普通刷新
                if (refreshCurrentMap) {
                    if (position != 0) {
                        return;
                    }
                    showCurrentMap();
                    Log.d(TAG, "refreshCurrentMap is true and refresh map");
                } else if (resetting) {
                    showCurrentMap();
                    resetting = false;
                    Log.d(TAG, "resetMap and refresh map");
                } else if (settingMap) {
                    settingMap = false;
                    position = 0;
                    showCurrentMap();
                    Log.d(TAG, "setMap and refresh map");
                }
                break;
            case Event.MSG_ROBOT_AREA:
                Log.d(TAG, "MSG_ROBOT_AREA1111");
                if (refreshCurrentMap || settingMap || resetting) {
                    Log.d(TAG, "MSG_ROBOT_AREA2222");
                    binding.targetView.refreshAreaLayer((List<AreaInfo>) event.getContent());
                }
                break;
            case Event.MESSAGE_TYPE_RESET_MAP_SUCCESS:
                LogUtils.i("MESSAGE_TYPE_RESET_MAP_SUCCESS");
                //重置地图后地图刷新
                if (loadProgressDialog.isShowing()) {
                    loadProgressDialog.dismiss();
                    ToastUtil.showShort(MapManagerActivity.this, R.string.MM_T_Reset_Ok);
                    LogUtils.i("地图已重置");
                }
                refreshCurrentMap = true;
                //清空原当前地图
                //AppContext.get().getCurrentDevice().getMap().clear();
                AppContext.getProductService().requestMap();
                break;
            case Event.MESSAGE_TYPE_USE_MAP:
                if (event.isResult()) {
                    if (settingMap) {
                        LogUtils.i("MESSAGE_TYPE_SET_MAP_SUCCESS");
                        position = 0;
                        //使用地图后地图刷新
                        loadProgressDialog.dismiss();
                        ToastUtil.showShort(MapManagerActivity.this, R.string.MM_T_UseMap_Ok);
                        LogUtils.i("地图加载完成");
                        //清空原当前地图
                        AppContext.get().getCurrentDevice().getMap().clear();
                        refreshCurrentMap = true;
                        AppContext.getProductService().requestMap();
                        settingMap = false;
                    }
                } else {
                    loadProgressDialog.dismiss();
                    ToastUtil.showShort(MapManagerActivity.this, R.string.MM_T_UseMap_No);
                    settingMap = false;
                }
                break;
            case Event.MSG_ROBOT_ROOM:
                if (refreshCurrentMap) {
                    binding.targetView.refreshRoomLayer((List<Room>) event.getContent());
                }
                break;
            case Event.MESSAGE_TYPE_SAVE_MULTI_MAP:
                if (event.isResult()) {
                    if (saving) {
                        if (loadProgressDialog.isShowing()) {
                            loadProgressDialog.dismiss();
                        }
                        getMultiMapDataList();
                        ToastUtil.showShort(MapManagerActivity.this, R.string.MM_T_Saved);
                        saving = false;
                    }
                } else {
                    if (loadProgressDialog.isShowing()) {
                        loadProgressDialog.dismiss();
                        ToastUtil.showShort(MapManagerActivity.this, R.string.MM_T_Saved_No);
                        saving = false;
                    }
                }
                break;
            case Event.MESSAGE_TYPE_GET_MAP_LIST:
                getMultiMapDataList();
                Log.d("testMultiMap", "MESSAGE_TYPE_GET_MULTI_MAP");
                break;
            case Event.MESSAGE_TYPE_DELETE_MULTI_MAP:
                if (event.isResult()) {
                    if (loadProgressDialog.isShowing() && deleting) {
                        getMultiMapDataList();
                        loadProgressDialog.dismiss();
                        ToastUtil.showShort(MapManagerActivity.this, R.string.MM_T_Delete_Ok);
                        deleting = false;
                        if (popupWindowRight != null) {
                            popupWindowRight.selectItem(0);
                        }
                        updateMapNameList();
                    }
                } else {
                    if (loadProgressDialog.isShowing()) {
                        loadProgressDialog.dismiss();
                        ToastUtil.showShort(MapManagerActivity.this, R.string.MM_T_Delete_No);
                        deleting = false;
                    }
                }

                break;
            case Event.MESSAGE_TYPE_RENAME_MULTI_MAP:
                if (event.isResult()) {
                    if (renaming) {
                        ToastUtil.showShort(MapManagerActivity.this, R.string.U_T_RobotName_Edit_Ok);
                        binding.tvMapManagerName.setText(selectedMapName);
                        selectItemBean.setName(selectedMapName);
                        getMultiMapDataList();
                        renaming = false;
                        Log.d(TAG, "rename map success toasting");
                        updateMapNameList();
                    }
                } else {
                    loadProgressDialog.dismiss();
                    ToastUtil.showShort(MapManagerActivity.this, R.string.U_T_RobotName_Edit_No);
                    renaming = false;
                }

                break;
            case Event.MSG_ROBOT_MULTI_MAP:
                showCurrentMap();
                break;
            case Event.MESSAGE_TYPE_DELETE_EQUIPMENT:
                SharedPrefsUtil.putValue(this, "USER_DEVICE_ID", "user_device_id", "");
                SharedPrefsUtil.putValue(this, Constants.DEVICEID, "deviceId", "");
                Intent_utils.backIntent(this, MainActivity2.class);
                break;
            case Event.MSG_ROBOT_OBJECT:
                binding.targetView.refreshObjectRecognitionLayer(AppContext.get().getCurrentDevice().getMap().getObjectList());
                break;
            case Event.MSG_ROBOT_FURNITURE:
                //binding.targetView.rLayer(AppContext.get().getCurrentDevice().getMap().getFurniture());
                break;
            default:
                break;
        }
    }

    @Override
    public void onSelected(int position) {
        this.position = position;
        boolean showCustom = AppContext.get().getCurrentDevice().getCleanSettings().isCustomSwitch();
        binding.targetView.setRoomTagMode(true, false, false, false, showCustom && (position == 0), productConfig.optBoolean(ProductConfigConstants.custom_cleanTimes), productConfig.optBoolean(ProductConfigConstants.custom_water));
        Log.d("testlll", "select current map,showCustom is " + showCustom);

        MapManagerItemBean mapManagerItemBean = multiMaplist.get(position);
        if (position != 0) {
            refreshCurrentMap = false;
            binding.targetView.clearMap();
            binding.targetView.initMap(mapManagerItemBean.getMap()); //-->mapView显示地图
            binding.flBottom.setVisibility(View.GONE);
            binding.llNoMap.setVisibility(View.GONE);
            binding.llBtnSetMapOk.setVisibility(View.VISIBLE);
            binding.ivMapRefresh.setVisibility(View.VISIBLE);
            binding.ivMapSave.setVisibility(View.VISIBLE);
            binding.ivMapRefresh.setImageResource(R.mipmap.map_manager_delete);
            binding.ivMapRefresh.setTag("delete");
            binding.ivMapSave.setImageResource(R.mipmap.map_manager_edit);
            binding.ivMapSave.setTag("edit");
        } else {
            showCurrentMap();
            refreshCurrentMap = true;
        }
        binding.tvMapManagerName.setText(mapManagerItemBean.getName());
        selectItemBean = multiMaplist.get(position);
    }

    void showCurrentMap() {
        if (binding.cb3d2dSwitch.isChecked()) {
            binding.map3dTargetView.refreshMap(AppContext.get().getCurrentDevice().getMap());
        } else {
            binding.targetView.initMap(AppContext.get().getCurrentDevice().getMap()); //-->mapView显示地图
        }
        refreshCurrentMapView();
    }

    private void currentTaskDialog(String content, int mode) {
        CommonConfirmDialog2.newBuilder()
                .context(this)
                //TODO 开启定位服务 没给文本
                .message(content)
                .confirmCallback(new CommonConfirmDialog2.ConfirmCallback() {
                    @Override
                    public boolean onConfirm() {
                        if (mode == RobotStatus.MODE_RECHARGE) {
                            //停止回充 152 false
                            AppContext.getProductService().stopRecharge();
                        } else {
                            //停止清扫
                            AppContext.getProductService().stopSweep();
                        }
                        Intent_utils.enterIntent(MapManagerActivity.this, AreaEditActivity.class);
                        return true;
                    }

                    @Override
                    public boolean onCancel() {
                        return true;
                    }
                }).build().show();
    }

    private void currentTaskDialog1(String content, int mode) {
        CommonConfirmDialog2.newBuilder()
                .context(this)
                //TODO 开启定位服务 没给文本
                .message(content)
                .confirmCallback(new CommonConfirmDialog2.ConfirmCallback() {
                    @Override
                    public boolean onConfirm() {
                        if (mode == RobotStatus.MODE_RECHARGE) {
                            //停止回充 152 false
                            AppContext.getProductService().stopRecharge();
                        } else {
                            //停止清扫
                            AppContext.getProductService().stopSweep();
                        }
                        Intent_utils.enterIntent(MapManagerActivity.this, RoomEditActivity.class);
                        return true;
                    }

                    @Override
                    public boolean onCancel() {
                        return true;
                    }
                }).build().show();
    }

    public static class MainHandler extends Handler {
        SoftReference<MapManagerActivity> mapManagerActivitySoftReference;

        public MainHandler(MapManagerActivity activity) {
            mapManagerActivitySoftReference = new SoftReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == Event.MESSAGE_TYPE_REQUEST_MAP_AND_PATH) {
                if (mapManagerActivitySoftReference.get() != null) {
                    mapManagerActivitySoftReference.get().requestMap();
                }
            }
        }
    }
}
